package com.wmh.baseservice.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wmh.baseservice.admin.pojo.AdGoods;
import com.wmh.baseservice.admin.service.AdGoodsService;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.FileUtil;
import com.wmh.baseservice.common.utils.UUIDUtil;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.system.pojo.SysCategory;
import com.wmh.baseservice.system.service.SysCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author wmh generator
 * @since 2021-12-27
 */
@Api(tags = "管理员端-平台商品相关接口")
@RestController
@RequestMapping(value = "admin/adGoods", produces = "text/plain;charset=utf-8")
@RequiresRoles("admin")
public class AdGoodsController {

    @Resource
    private AdGoodsService adGoodsService;
    @Resource
    private SysCategoryService sysCategoryService;


    @ApiOperation("list")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, String name, Long categoryId) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<AdGoods> pageResult = new PageUtil<AdGoods>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(name)) {
                queryWrapper.like(AdGoods.TITLE, name);
            }
            if (CommUtil.checkNull(categoryId)){
                queryWrapper.eq(AdGoods.CATEGORY_ID,categoryId);
            }
            adGoodsService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            SysCategory sysCategory = sysCategoryService.getByIdForUpdate(item.getCategoryId());
            if (CommUtil.checkNull(sysCategory)) {
                item.setCategoryName(sysCategory.getName());
            }
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("添加商品")
    @PostMapping("addGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"title", "categoryId", "avatar", "overview", "content", "price", "inventory"})
    public String addGoods(String title, Long categoryId, String avatar, String img, String overview, String content, MultipartFile video, Integer inventory, Long urlId, BigDecimal price) {
        JSONArray imgList = new JSONArray();
        AdGoods adGoods = new AdGoods().setTitle(title).setCategoryId(categoryId).setOverview(overview).setContent(content).setInventory(inventory).setUrlId(urlId).setPrice(price);
        if (!CommUtil.checkNull(urlId)) {
            urlId = UUIDUtil.getTimeId();
            adGoods.setUrlId(urlId);
        }
        if (CommUtil.checkNull(avatar) && avatar.contains("base64")) {
            String url = Base64Util.generateImage("goods/" + urlId, avatar);
            if (!CommUtil.checkNull(url)) {
                return ReturnBody.error("图片上传错误");
            }
            adGoods.setAvatar(url);
        }
        if (CommUtil.checkNull(img)) {
            JSONArray array = JSONArray.parseArray(img);
            Long finalUrlId = urlId;
            array.forEach(item -> {
                String itemImg = String.valueOf(item);
                itemImg = Base64Util.generateImage("goods/" + finalUrlId, item.toString());
                if (!CommUtil.checkNull(itemImg)) {
                    throw new ServiceException("图片上传错误");
                }
                imgList.add(itemImg);
            });
            adGoods.setImg(imgList.toJSONString());
        }
        if (CommUtil.checkNull(video)) {
            String upload = FileUtil.upload("goods/" + urlId, video, "file");
            if (CommUtil.checkNull(upload)) {
                adGoods.setVideo(upload);
            }
        }
        if (!adGoodsService.save(adGoods)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("修改商品")
    @PostMapping("updateGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id", "title", "categoryId", "avatar", "overview", "content", "price", "inventory"})
    public String updateGoods(Long id, String title, Long categoryId, String avatar, String img, String overview, String content, MultipartFile video, Integer inventory, BigDecimal price,boolean hasVideo) {
        AdGoods adGoods = adGoodsService.getByIdForUpdate(id);
        //1.主图处理
        if (CommUtil.checkNull(avatar)) {
            if (avatar.contains("base64")) {
                FileUtil.delete(adGoods.getAvatar());
                String url = Base64Util.generateImage("goods/" + adGoods.getUrlId(), avatar);
                if (!CommUtil.checkNull(url)) {
                    return ReturnBody.error("图片上传错误");
                }
                adGoods.setAvatar(url);
            } else {
                adGoods.setAvatar(avatar);
            }
        }

        //2.轮播图处理
        JSONArray imgArray = new JSONArray();
        if (CommUtil.checkNull(img)) {
            //2.1如果图片列表包含base64新上传的编码，则遍历每一个，如果是路径，取出放在上面的数组中，如果是base64，则保存后再存入数组
            JSONArray array = JSONArray.parseArray(img);
            array.forEach(item -> {
                String url = String.valueOf(item);
                if (url.contains("base64")) {
                    url = Base64Util.generateImage("goods/" + adGoods.getUrlId(), item.toString());
                    if (!CommUtil.checkNull(url)) {
                        throw new ServiceException("图片上传错误");
                    }
                }
                imgArray.add(url);
            });
            //比较然后判断
            if (CommUtil.checkNull(adGoods.getImg())) {
                List<String> list = FileUtil.getList(adGoods.getImg(), imgArray);
                if (list.size() != 0) {
                    list.forEach(item -> FileUtil.delete(item));
                }
            }
            adGoods.setImg(imgArray.toJSONString());
        }
        //2.2轮播图为空设置为null保证修改的时候可上传
        if (!CommUtil.checkNull(img) || img.equals("[\"\"]")) {
            adGoods.setImg(null);
        }

        //3.视频处理
        if (CommUtil.checkNull(video)) {
            //3.1删除之前的视频
            if (CommUtil.checkNull(adGoods.getVideo())) {
                FileUtil.delete(adGoods.getVideo());
            }
            String upload = FileUtil.upload("goods/" + adGoods.getUrlId(), video, "file");
            if (CommUtil.checkNull(upload)) {
                adGoods.setVideo(upload);
            }
        } else {
            //3.4没有视频,如果之前有视频则删除视频文件
            if (CommUtil.checkNull(adGoods.getVideo()) && !hasVideo) {
                FileUtil.delete(adGoods.getVideo());
                adGoods.setVideo(null);
            }
        }
        //3.2比较前后html是否一致
        if (CommUtil.checkNull(content)) {
            List<String> imgList = FileUtil.getImgElementList(adGoods.getContent(), content);
            if (imgList.size() != 0) {
                //3.3删除富文本删除的图片
                imgList.forEach(item -> FileUtil.delete(item));
            }
            adGoods.setContent(content);
        }

        //4.对剩下的参数进行赋值
        adGoods.setTitle(title).setCategoryId(categoryId).setOverview(overview).setInventory(inventory).setPrice(price);
        if (!adGoodsService.updateById(adGoods)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("删除商品")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id"})
    public String delete(Long id) {
        AdGoods adGoods = adGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(adGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        adGoodsService.delete(adGoods);
        return ReturnBody.success();
    }

    @ApiOperation("上下架商品")
    @PostMapping("upOrDown")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String upOrDown(Long id) {
        AdGoods adGoods = adGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(adGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        adGoods.setStatus(adGoods.getStatus() == 0 ? -1 : 0);
        if (!adGoodsService.updateById(adGoods)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("图片上传")
    @PostMapping("uploadImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String uploadImg(MultipartFile[] file, Long urlId) {
        JSONObject object = new JSONObject();
        Long timeId = 0L;
        //生成随机id文件夹
        if (CommUtil.checkNull(urlId)) {
            timeId = urlId;
        } else {
            timeId = UUIDUtil.getTimeId();
        }
        List<String> uploads = FileUtil.uploads("goods/" + timeId, file, "file");
        if (!CommUtil.checkNull(uploads)) {
            return ReturnBody.error("图片上传错误");
        }
        //返回随机id，前端添加商品时传给数据库存储该文件夹字段，方便后面删除商品的时候把图片一起删除
        object.put("uploads", uploads);
        object.put("id", timeId);
        return ReturnBody.success(object);
    }

    @ApiOperation("删除图片")
    @PostMapping("deleteImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String deleteImg(String array) {
        JSONArray jsonArray = JSONArray.parseArray(array);
        jsonArray.forEach(item -> {
            FileUtil.delete(item.toString());
        });
        return ReturnBody.success();
    }


}
